package tr.edu.metu.is550.isell.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import tr.edu.metu.is550.isell.R;
import tr.edu.metu.is550.isell.utils.CryptoUtils;

public class AddPropertyActivity extends Activity {
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (Activity.RESULT_OK != resultCode)
            return;

        Double lat = (Double) data.getExtras().get("lat");
        Double lon = (Double) data.getExtras().get("lon");

        ((EditText) findViewById(R.id.txtLatitude)).setText(String.valueOf(lat));
        ((EditText) findViewById(R.id.txtLongitude)).setText(String.valueOf(lon));

    }

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_property);
        final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

        Button btnAddProperty = (Button) findViewById(R.id.btnAddProperty);
        Button btnShowMap = (Button) findViewById(R.id.btnShowMap);

        btnShowMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), MapsActivity.class);
                startActivityForResult(myIntent, 1);
            }
        });


        btnAddProperty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String serverURL = sp.getString("pref_dialog", "NULL");

                    DefaultHttpClient client = new DefaultHttpClient();


                    JSONObject property = new JSONObject();
                    JSONObject detail = new JSONObject();
                    detail.put("title", ((EditText) findViewById(R.id.txtTitle)).getText())
                            .put("details", ((EditText) findViewById(R.id.txtDetails)).getText())
                            .put("address", ((EditText) findViewById(R.id.txtAddress)).getText())
                            .put("price", ((EditText) findViewById(R.id.txtPrice)).getText())
                            .put("adtype", ((RadioButton) findViewById(R.id.radio_sale)).isChecked() ? 1 : 0)
                            .put("propertyType", ((RadioButton) findViewById(R.id.radio_flat)).isChecked() ? 1 : 0)
                            .put("latitude", ((EditText) findViewById(R.id.txtLatitude)).getText())
                            .put("longitude", ((EditText) findViewById(R.id.txtLongitude)).getText())
                            .put("numberOfRooms", ((EditText) findViewById(R.id.txtNumberOfRooms)).getText());
                    property.put("property", detail);


                    HttpPost httpPost = new HttpPost(serverURL + "/property");
                    httpPost.setHeader("Content-Type", "application/json");
                    httpPost.setHeader("Accept", "application/json");
                    httpPost.setHeader("Authorization", "ISell " + CryptoUtils.encryptAndBase64Encode(getApplicationContext(), sp.getString("userName", "") + ":" + sp.getString("password", "")));
                    httpPost.setEntity(new ByteArrayEntity(property.toString().getBytes()));

                    HttpResponse response = client.execute(httpPost);

                    int statusCode = response.getStatusLine().getStatusCode();

                    if (HttpStatus.SC_CREATED == statusCode) {
                        Toast.makeText(getApplicationContext(), "Property Added", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (HttpStatus.SC_UNAUTHORIZED == statusCode) {
                        Toast.makeText(getApplicationContext(), "Not Authorized!", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    throw new RuntimeException("An exception occured during add property!");

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

}
